package servlet;

import dao.BlogDao;
import entity.Blog;
import entity.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: ZhangYufei
 * Date: 2021-07-22
 * Time: 17:19
 */
@WebServlet("/blogDelete")
public class BlogDeleteServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1. 从 req 中读取要删除的blogId
        String blogId = req.getParameter("blogId");
        if (blogId == null || "".equals(blogId)) {
            resp.sendError(404, "blogId为空");
            return;
        }
        int id = Integer.parseInt(blogId);
        //2. 判定用户的登录状态，未登录不能删除
        HttpSession session = req.getSession(false);
        if (session == null) {
            resp.sendError(404, "当前未登录，不能删除博客");
            return;
        }
        User User = (User) session.getAttribute("user");
        if (User == null) {
            resp.sendError(404, "当前未登录，不能删除博客");
            return;
        }
        //3. 根据blogId查询blogId的作者userId，看当前登录的用户id和userId是否相同，如果不相同则不能删除
        //4. 如果相同，从数据库中删除该blog
        BlogDao blogDao = new BlogDao();
        Blog blog = blogDao.selectOne(id);
        if (blog == null) {
            resp.sendError(404, "当前博客不存在");
            return;
        }
        if (blog.getUserId() != User.getId()) {
            resp.sendError(403, "不能删除其他作者的博客");
            return;
        }
        //4. 如果相同，从数据库中删除该blog
        blogDao.delete(id);
        //5. 重定向到博客列表页
        resp.sendRedirect("blogList");
    }
}
